package com.ysd.lis.service.bac.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysd.lis.entity.bac.BacBreakPointLog;
import com.ysd.lis.mapper.bac.BacBreakPointLogMapper;
import com.ysd.lis.service.bac.BacBreakPointLogService;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wh
 * @since 2025-05-22
 */
@Service
public class BacBreakPointLogServiceImpl extends ServiceImpl<BacBreakPointLogMapper, BacBreakPointLog> implements BacBreakPointLogService {

    @Override
    public void addPointLog(BacBreakPointLog bacBreakPointLog) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        String ip = getIp(request);
        String machineName = getMachineName();
        bacBreakPointLog.setMachineIp(ip);
        bacBreakPointLog.setMachineName(machineName);
        this.save(bacBreakPointLog);
    }

    public static String getIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip.contains(",")) {
            return ip.split(",")[0];
        } else {
            return ip;
        }
    }
    public static String getMachineName() {
        try {
            InetAddress localHost = InetAddress.getLocalHost();
            return localHost.getHostName();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
